<template>
  <div class="w-full">
    <!-- 头部表单 -->
    <el-row :gutter="24" style="margin-bottom: 0px">
      <el-col :offset="1" :span="22" style="margin-top: 10px">
        <!-- 遍历搜索字段 -->
        <Forms :list="pageSetting.search" :name="'AppApiPage'" />
      </el-col>
    </el-row>
    <el-row :gutter="24" style="margin-top: 10px">
      <el-col :offset="1" :span="22">
        <el-tabs v-model="tabName" type="card" @tab-click="handleClick">
          <el-tab-pane v-for="(item, index) of tabList" :key="index" :label="item.title" :name="item.name">
            <div class="bg-purple">
              <div class="grid-content">
                <template v-for="(v, i) in tableTopList" :key="i">
                  <el-button
                    v-if="v.FUNCTION_URI != 'import' && v.FUNCTION_URI != 'export' && v.FUNCTION_URI != 'copy'"
                    style="margin-left: 0"
                    @click="showDialog('add', index + 1)"
                  >
                    {{ v.BUTTON_NAME }}
                  </el-button>
                  <vui-upload
                    v-if="uploadOptions.url && item.name == 'first' && v.FUNCTION_URI == 'import'"
                    ref="fileUploadRef"
                    :auto-upload="true"
                    :file-name="uploadOptions.name"
                    :limit="1"
                    :post-data="uploadOptions.postData"
                    :show-file-list="false"
                    :url="uploadOptions.url"
                    @uploadSuccess="uploadSuccess"
                  >
                    <el-button>{{ translateTitle('Dams.ApplicationInterface.导入') }}</el-button>
                  </vui-upload>
                  <el-button v-show="item.name == 'first' && v.FUNCTION_URI == 'export'" style="margin-left: 0" @click="exportBtn()">导出</el-button>
                  <el-button v-show="v.FUNCTION_URI == 'copy'" style="margin-left: 0" @click="copyColumn">
                    {{ translateTitle('Dams.ApplicationInterface.复制') }}
                  </el-button>
                </template>
                <el-button v-show="tabName == 'first'" style="margin-left: 0" @click="testColumn">
                  {{ translateTitle('Dams.ApplicationInterface.接口测试') }}
                </el-button>
              </div>

              <Table
                v-loading="loading2"
                :column-list="tbData(`t${index + 1}`)"
                :get-height="getHeight"
                :loading="tableLoading"
                :name="'AppApiPage'"
                :style="{ height: `${getHeight}px` }"
                :tables="tables[`t${index + 1}`]"
              />
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-col>
    </el-row>

    <!-- 弹框 -->
    <el-dialog
      v-model="dialogVisible"
      :close-on-click-modal="false"
      :title="translateTitle('Dams.ApplicationInterface.增删改查')"
      width="80%"
      @close="hasDialogOpen = !hasDialogOpen"
      @open="hasDialogOpen = !hasDialogOpen"
    >
      <div class="dialog-box">
        <Forms
          v-if="dialogVisible"
          :data-from="formData"
          :dialog-num="DialogNum"
          :list="pageSetting.dialog"
          :name="'AppApiPage'"
          :open="hasDialogOpen"
          :type="dialogType"
        />
      </div>
    </el-dialog>
    <el-dialog v-model="testdialogVisible" :close-on-click-modal="false" :title="translateTitle('Dams.ApplicationInterface.接口测试')" width="80%">
      <div class="dialog-box">
        <el-form ref="ruleForm" :inline="true" label-position="top" :model="saveTestformData">
          <el-form-item class="item_line">
            <div class="line">{{ translateTitle('Dams.ApplicationInterface.请求信息') }}</div>
          </el-form-item>
          <el-form-item :label="translateTitle('Dams.ApplicationInterface.接口地址')">
            <el-input v-model="saveTestformData.API_ADDR" :clearable="true" :placeholder="translateTitle('Dams.ApplicationInterface.请输入内容')" />
          </el-form-item>
          <el-form-item :label="translateTitle('Dams.ApplicationInterface.接口环境')">
            <el-select v-model="saveTestformData.ENV" :clearable="true" @change="changeSelect">
              <el-option v-for="item in testOptions" :key="item.LABEL" :label="item.LABEL" :value="item.CODE" />
            </el-select>
          </el-form-item>
          <el-form-item :label="translateTitle('Dams.ApplicationInterface.导入')">
            <vui-upload
              :ref="`fileUploadRefTest`"
              file-name="uploadFile"
              :limit="1"
              :post-data="
                saveTestformData.REQUEST_MSG
                  ? { method: saveTestformData.API_NAME, data: saveTestformData.REQUEST_MSG }
                  : { method: saveTestformData.API_NAME }
              "
              :show-file-list="true"
              :url="apiUrl"
              @uploadSuccess="uploadSuccess1"
            >
              <el-button>{{ translateTitle('Dams.ApplicationInterface.导入') }}</el-button>
            </vui-upload>
          </el-form-item>
          <el-form-item :label="translateTitle('Dams.ApplicationInterface.是否导出导出默认xlsx格式')">
            <!-- <el-button type="primary">导出</el-button> -->
            <el-switch v-model="saveTestformData.switch" active-color="#13ce66" />
          </el-form-item>
          <el-form-item class="item_textarea" :label="translateTitle('Dams.ApplicationInterface.data参数')">
            <CodeEditor :ref="'VuiCodeEditor_'" v-model="saveTestformData.REQUEST_MSG" />
          </el-form-item>
          <el-form-item class="item_textarea" :label="translateTitle('Dams.ApplicationInterface.备注')">
            <CodeEditor :ref="'VuiCodeEditor_'" v-model="saveTestformData.NOTES" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="testRequest">{{ translateTitle('Dams.ApplicationInterface.请求') }}</el-button>
            <el-button type="primary" @click="saveRequest">{{ translateTitle('Dams.ApplicationInterface.保存') }}</el-button>
          </el-form-item>
          <el-form-item class="item_line">
            <div class="line">{{ translateTitle('Dams.ApplicationInterface.响应信息') }}</div>
          </el-form-item>
          <el-form-item class="item_textarea" :label="translateTitle('Dams.ApplicationInterface.响应报文')">
            <CodeEditor :ref="'VuiCodeEditor_'" v-model="saveTestformData.RESPONSE" />
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { Mixin } from '@/common/minxin/Mixin'
  import { GFCD } from '@/utils/utils'
  import Forms from '../../components/forms'
  import Table from '../../components/table'
  import CodeEditor from '../../components/codeEditor'
  import { getList, download } from '../../api/home'
  import debounce from 'lodash/debounce'
  import cloneDeep from 'lodash/cloneDeep'
  import trim from 'lodash/trim'
  import AppApiPage from '../../components/json/AppApiPage'
  import { translateTitle } from '@/utils/i18n'
  const configSetting = GFCD('dams')
  export default {
    name: 'AppApiPage',
    components: {
      Forms,
      Table,
      CodeEditor,
    },
    mixins: [Mixin],
    data() {
      return {
        tableLoading: false,
        testOptions: [
          {
            LABEL: translateTitle('Dams.ApplicationInterface.测试环境'),
            CODE: '测试环境',
          },
          {
            LABEL: translateTitle('Dams.ApplicationInterface.正式环境'),
            CODE: '正式环境',
          },
          {
            LABEL: translateTitle('Dams.ApplicationInterface.本地环境'),
            CODE: '本地环境',
          },
        ],
        saveTestType: '',
        portForm: {},
        testdialogVisible: false,
        saveTestformData: {},
        uploadOptions: {
          postData: {
            method: 'dams.config.import',
          },
          name: 'uploadFile',
          url: `${configSetting.domain}${configSetting.baseUrl}`,
        },
        clientHeight: 0,
        unsubs: [],
        hasDialogOpen: false,
        tabName: 'first', //选项卡
        serData: {}, //搜索表单内容
        configSetting: {},
        pageSetting: {
          dialog: {
            form: {
              field: [],
              fieldMapping: [],
              fieldMapping3: [],
              fieldMapping4: [],
            },
          },
          search: {
            form: {
              field: [],
            },
          },
        },
        dialogVisible: false,
        // 选项卡列表
        tabList: [
          { name: 'first', title: translateTitle('Dams.ApplicationInterface.第一步配置接口处理流程参数') },
          { name: 'second', title: translateTitle('Dams.ApplicationInterface.第二步配置SQL映射报文字段') },
          { name: 'thrid', title: translateTitle('Dams.ApplicationInterface.第三步配置追加SQL映射报文字段') },
          { name: 'four', title: translateTitle('Dams.ApplicationInterface.第四步配置字段映射和验证规则') },
        ],
        tables: {
          t1: {
            export: true,
            columnList: [], //表格头名称
            tableList: [], //表格列表
            name: 't1',
            count: 0, //分页总数
            pageSize: 50, //当前页面几条
            radioCheck: {}, //单选选中
            tablePage: {
              '#LIMIT#': 1,
              '#PAGE_SIZE#': 50,
            },
            dbClick: {}, //双击选中参数
            dbPost: {}, //双击请求接口的参数
          },
          t2: {
            export: true,
            columnList: [], //表格头名称
            tableList: [], //表格列表
            name: 't2',
            count: 0, //分页总数
            pageSize: 50, //当前页面几条
            radioCheck: {}, //单选选中
            tablePage: {
              '#LIMIT#': 1,
              '#PAGE_SIZE#': 50,
            },
            dbClick: {}, //双击选中参数
            dbPost: {}, //双击请求接口的参数
          },
          t3: {
            export: true,
            columnList: [], //表格头名称
            tableList: [], //表格列表
            name: 't3',
            count: 0, //分页总数
            pageSize: 50, //当前页面几条
            radioCheck: {}, //单选选中
            tablePage: {
              '#LIMIT#': 1,
              '#PAGE_SIZE#': 50,
            },
            dbClick: {}, //双击选中参数
            dbPost: {}, //双击请求接口的参数
          },
          t4: {
            export: true,
            columnList: [], //表格头名称
            tableList: [], //表格列表
            name: 't4',
            count: 0, //分页总数
            pageSize: 50, //当前页面几条
            radioCheck: {}, //单选选中
            tablePage: {
              '#LIMIT#': 1,
              '#PAGE_SIZE#': 50,
            },
            dbClick: {}, //双击选中参数
            dbPost: {}, //双击请求接口的参数
          },
        },
        loading1: false,
        loading2: false,
        loading3: false,
        loading4: false,
        formData: {},
        postData: {},
        defaultDrop: [], //下拉数据
        dialogType: '',
        DialogNum: 0,
        deleteNum: 0,
        delectName: '',
        //是否点击了刷新缓存
        isRefresh: false,
        // 是否校验了sql
        testSql: false,
        // 添加接口地址
        addPostUrl: '',
        // 修改接口地址
        modifyPostUrl: '',
        // 选中删除
        delData: {},
        // 第三步需要的
        threeObj: {
          isclick2: false,
        },
        checkboxData: [], //复选框数据
        checkboxData2: [],
        checkboxData3: [],
        checkboxData4: [],
        tableTopList: [],
        helpList: [],
      }
    },
    computed: {
      getHeight() {
        return `${this.clientHeight - 265}`
      },
      apiUrl() {
        return this.saveTestformData.API_ADDR
      },
    },
    watch: {
      DialogNum: {
        deep: true,
        handler(newval) {
          this.formDataShow(newval)
        },
      },
      dialogVisible() {
        if (!this.dialogVisible && this.dialogType == 'modify') {
          this.formData = {}
        }
      },
    },
    unmounted() {
      this.unsubs.forEach((v) => {
        this.$unsub(v)
      })
    },
    created() {
      this.getHelp()
      this.init()
    },
    methods: {
      translateTitle,
      async getHelp() {
        let res = await getList(`${configSetting.domain}${configSetting.baseUrl}`, {
          method: 'dams.api.config.help.query',
          data: JSON.stringify({
            '#LIMIT#': 1,
            '#PAGE_SIZE#': 9999,
          }),
        })
        this.helpList = res.data
        console.log(res)
      },
      async changeSelect(e) {
        console.log(this.saveTestformData.API_ADDR)
        // if (name == 'ENV') {
        console.log(this.saveTestformData)
        this.saveTestformData.ENV = e
        let res = await getList(`${configSetting.domain}${configSetting.baseUrl}`, {
          method: '*.api.test',
          data: JSON.stringify({
            ENV: this.saveTestformData.ENV,
            API_NAME: this.saveTestformData.API_NAME,
            SUB_SYSTEM: this.saveTestformData.SUB_SYSTEM,
            '#LIMIT#': 1,
            '#PAGE_SIZE#': 9999,
          }),
        })
        console.log(res)
        if (res.data['*.api.test'].data.length > 0) {
          this.saveTestformData = res.data['*.api.test'].data[0]
        } else {
          this.saveTestformData.API_ADDR = ''
          this.saveTestformData.REQUEST_MSG = ''
          this.saveTestformData.RESPONSE = ''
          this.saveTestformData.NOTES = ''
        }
        // this.saveTestformData = res.data['*.api.test'].data ?res.data['*.api.test'].data[0]
        // }
      },
      getBracketData(str) {
        if (str.indexOf('{') != -1 && str.indexOf('}') != -1) {
          let a1 = /\{(.+?)\}/g //正则获取小括号
          let a2 = str.match(a1).toString() //因为输出的是数组，所以得转化成字符串
          var a3 = a2.replace('{', '') //用空字符替换掉括号
          a3 = a3.replace('}', '')
          console.log(a3) //最终得到括号里面的数字
          return a3
        }
      },
      uploadSuccess1(file) {
        let res = file.fileList[0].response
        this.$message({
          type: this.getBracketData(res.msg),
          message: res.msg,
        })
        this.saveTestformData.RESPONSE = JSON.stringify(res, null, 4)
      },
      validateJSON(data) {
        if (typeof data == 'string') {
          try {
            var obj = JSON.parse(data)
            if (typeof obj == 'object' && obj) {
              return true
            } else {
              return false
            }
          } catch (e) {
            return false
          }
        }
      },
      disableApi(data) {
        console.log(data)
        this.Model(`${translateTitle('Dams.ApplicationInterface.是否禁用')}?`, () => {
          let url = `${this.configSetting.domain}${this.configSetting.baseUrl}`
          getList(url, {
            data: JSON.stringify({
              API_NAME: data.API_NAME,
              SUB_SYSTEM: data.SUB_SYSTEM,
            }),
            method: '*.standard.disable.api',
          }).then((res) => {
            this.$baseMessage(res.msg, 'success')
            this.onSubmit(
              this.serData,
              {
                '#LIMIT#': 1,
                '#PAGE_SIZE#': 50,
              },
              1
            )
          })
        })
      },
      testColumn() {
        if (this.checkboxData.length == 0)
          return this.$message({ message: translateTitle('Dams.ApplicationInterface.请选择数据后再进行测试'), type: 'error' })
        if (this.checkboxData.length > 1)
          return this.$message({ message: translateTitle('Dams.ApplicationInterface.只能选择一项数据进行测试'), type: 'error' })
        let url = `${this.configSetting.domain}${this.configSetting.baseUrl}`
        getList(url, {
          data: JSON.stringify({
            API_NAME: this.checkboxData[0].API_NAME,
            SUB_SYSTEM: this.checkboxData[0].SUB_SYSTEM,
            '#LIMIT#': 1,
            '#PAGE_SIZE#': 9999,
          }),
          method: '*.api.test',
        }).then((res) => {
          console.log(res)
          this.testdialogVisible = true
          if (res.data['*.api.test'].data.length > 0) {
            this.saveTestformData = res.data['*.api.test'].data[0]
          } else {
            this.saveTestformData = {
              API_NAME: this.checkboxData[0].API_NAME,
              SUB_SYSTEM: this.checkboxData[0].SUB_SYSTEM,
            }
          }
        })
      },
      //测试接口--请求
      testRequest() {
        console.log(this.saveTestformData)
        console.log(this.$refs['fileUploadRefTest'])
        if (this.saveTestformData.switch) {
          let url = this.saveTestformData.API_ADDR
          download(url, {
            method: this.saveTestformData.API_NAME,
            data: this.saveTestformData.REQUEST_MSG,
          }).then((res) => {
            let blob = new Blob([res], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
            let a = document.createElement('a')
            a.download = `${translateTitle('Dams.ApplicationInterface.导出测试数据')}.xlsx`
            a.href = URL.createObjectURL(blob)
            a.click()
          })
        } else {
          if (this.$refs['fileUploadRefTest'].allImgNum) {
            this.$refs['fileUploadRefTest'].submitUpload()
          } else {
            if (!this.validateJSON(this.saveTestformData.REQUEST_MSG))
              return this.$baseMessage(translateTitle('Dams.ApplicationInterface.data参数JSON格式错误'), 'error')
            getList(this.saveTestformData.API_ADDR, {
              data: this.saveTestformData.REQUEST_MSG,
              method: this.saveTestformData.API_NAME,
            })
              .then((res) => {
                this.$message({
                  type: 'success',
                  message: res.msg,
                })
                this.saveTestformData.RESPONSE = JSON.stringify(res, null, 4)
              })
              .catch((err) => {
                this.saveTestformData.RESPONSE = JSON.stringify(err, null, 4)
              })
          }
        }
      },
      getMsg(row) {
        let url = `${this.configSetting.domain}${this.configSetting.baseUrl}`
        getList(url, {
          data: JSON.stringify(row),
          method: '*.api.test',
        }).then((res) => {
          this.$message({
            type: 'success',
            message: res.msg,
          })
        })
      },
      //测试接口--保存
      saveRequest() {
        let url = `${this.configSetting.domain}${this.configSetting.baseUrl}`
        getList(url, {
          data: JSON.stringify(this.saveTestformData),
          method: '*.api.test.update',
        }).then((res) => {
          this.$message({
            type: 'success',
            message: res.msg,
          })
        })
      },
      copyColumn() {
        console.log(this.checkboxData, this.DialogNum)
        let list = []
        if (this.DialogNum == 0) this.DialogNum++
        switch (this.DialogNum) {
          case 1:
            list = this.checkboxData
            break
          case 2:
            list = this.checkboxData2
            break
          case 3:
            list = this.checkboxData3
            break
          case 4:
            list = this.checkboxData4
            break
          default:
            break
        }
        console.log(list)
        if (list.length == 0) return this.$message({ message: translateTitle('Dams.ApplicationInterface.请选择数据后再进行复制'), type: 'error' })
        if (list.length > 1) return this.$message({ message: translateTitle('Dams.ApplicationInterface.只能选择一项数据进行复制'), type: 'error' })
        let form = cloneDeep(list[0])
        console.log(form)
        delete form.ID
        let arr = this.fieldType(this.DialogNum)
        this.dialogType = 'add'
        arr.forEach((v) => {
          if (!v.hidden) {
            if (v.type == 'select') {
              if (this.defaultDrop[v.name]) {
                v.options = this.defaultDrop[v.name].data
              }
            }
          }
        })

        this.fieldType(this.DialogNum).forEach((v) => {
          if (!v.hidden) {
            if (v.type == 'input' || v.type == 'textarea') {
              this.formData[v.name] = form[v.name]
            } else if (v.type == 'select') {
              if (
                // 存在，的情况
                v.name == 'FILE_TYPE' &&
                form['FILE_TYPE'] != ''
              ) {
                form[v.name].indexOf(',') != -1 ? (this.formData[v.name] = form[v.name].split(',')) : (this.formData[v.name] = [form[v.name]])
              } else {
                this.formData[v.name] = form[v.name]
              }
            }
          }
        })
        this.dialogVisible = true
      },
      uploadSuccess(file) {
        let res = file.fileList[file.fileList.length - 1].response
        if (res.code == '00000') {
          this.$message({
            type: 'success',
            message: translateTitle('Dams.ApplicationInterface.导入成功'),
          })
        } else {
          this.$message({
            type: 'error',
            message: res.msg,
          })
        }
        console.log('this.$refs', this.$refs['fileUploadRef'])
        this.$refs['fileUploadRef'].$refs.upload.clearFiles()
      },
      exportBtn() {
        if (this.checkboxData.length == 0) return this.$message({ message: translateTitle('Dams.ApplicationInterface.请选择数据'), type: 'error' })
        // 导出按钮
        this.Model(`${translateTitle('Dams.ApplicationInterface.确认导出')}?`, () => {
          //
          let obj = []
          this.checkboxData.forEach((it) => {
            obj.push({
              API_NAME: it.API_NAME,
              SUB_SYSTEM: it.SUB_SYSTEM,
            })
          })
          this.exportFuc(obj)
        })
      },
      // 导出接口
      exportFuc(row) {
        let url = `${this.configSetting.domain}${this.configSetting.baseUrl}`
        download(url, {
          method: 'dams.config.export',
          data: JSON.stringify(row),
        }).then((res) => {
          let blob = new Blob([res], { type: 'text/plain,charset=UTF-8' })
          let a = document.createElement('a')
          a.download = `${translateTitle('Dams.ApplicationInterface.导出接口数据')}.txt`
          a.href = URL.createObjectURL(blob)
          a.click()
        })
      },
      // 模态框
      Model(text, cb) {
        this.$confirm(text, translateTitle('Dams.ApplicationInterface.提示'), {
          confirmButtonText: translateTitle('Dams.ApplicationInterface.确定'),
          cancelButtonText: translateTitle('Dams.ApplicationInterface.取消'),
          type: 'warning',
        })
          .then(() => {
            if (cb) cb()
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: translateTitle('Dams.ApplicationInterface.已取消'),
            })
          })
      },
      setTooltip(list, num) {
        list.forEach((row) => {
          for (const key in this.helpList) {
            const element = this.helpList[key]
            if (key == row.name && element.data && element.data[0] && element.data[0].POSTION == num) {
              row.slot = true
              row.slotContent = element.data[0].HELP_CONTENT
            }
          }
          if (row.name == 'NATIVE_SQL') {
            row.slotContent = translateTitle('Dams.ApplicationInterface.注意如果是mybatisSQL写法1')
          }
        })
      },
      //获取子系统下拉数据
      async getSubsystemData() {
        let method = 'dams.handle.flow.query.options'
        let res = await getList(`${this.configSetting.domain}${this.configSetting.baseUrl}`, {
          method: method,
          data: JSON.stringify({ '#LIMIT#': 1, '#PAGE_SIZE#': 9999 }),
        })
        return res.data.SUB_SYSTEM.data
      },
      windowResize: debounce(function () {
        this.clientHeight = document.documentElement.clientHeight
      }, 100),
      async init() {
        this.configSetting = GFCD('dams')
        let menuBtns = this.$store.getters['user/menuBtns']
        menuBtns.forEach((row) => {
          if (this.$route.name.indexOf(row.MENU_CODE) > -1 && row.SHOW_POSTION == 'tableTop') {
            this.tableTopList.push(row)
          }
        })
        console.log(this.tableTopList)
        let res = await this.getSubsystemData()
        let list = []
        res.forEach((item) => {
          list.push({ CODE: item.CODE, LABEL: item.LABEL })
        })
        // this.nowJsonData().then((data) => {
        // this.pageSetting = data.AppApiPage
        this.pageSetting = AppApiPage
        let listField = this.pageSetting.search.form.field
        let pageSetDialog = this.pageSetting.dialog.form
        this.setTooltip(pageSetDialog.field, '1')
        this.setTooltip(pageSetDialog.fieldMapping, '2')
        this.setTooltip(pageSetDialog.fieldMapping3, '3')
        this.setTooltip(pageSetDialog.fieldMapping4, '4')
        listField.forEach((item) => {
          if (item.name == 'SUB_SYSTEM') {
            item.options = list
          }
        })
        this.eventInit()
        this.addSelect()
        this.windowResize()
        // })
        this.uploadOptions.url = `${this.configSetting.domain}${this.configSetting.baseUrl}`
      },
      handleClick(tab) {
        this.DialogNum = Number(tab.index) + 1
      },
      getTable(info) {
        let num = 0
        if (typeof info == 'number') {
          num = info
        } else {
          num = Number(info.replace(/[^0-9]/gi, ''))
        }
        return this.tables[`t${num}`]
      },
      // 表格渲染按钮接口地址定义
      formDataShow(num) {
        switch (num) {
          case 1:
            this.addPostUrl = 'dams.handle.flow.add'
            this.modifyPostUrl = 'dams.handle.flow.edit'
            break
          case 2:
            this.addPostUrl = 'dams.sql.field.map.add'
            this.modifyPostUrl = 'dams.sql.field.map.edit'
            break
          case 3:
            this.addPostUrl = 'dams.sql.add.map.add'
            this.modifyPostUrl = 'dams.sql.add.map.edit'
            break
          case 4:
            this.addPostUrl = 'dams.field.map.add'
            this.modifyPostUrl = 'dams.field.map.edit'
            break
        }
      },
      // 处理表头
      tbData(type) {
        let num = Number(type.replace(/[^0-9]/gi, ''))
        let arr = this.fieldType(num)
        let newArr = []

        arr.forEach((v) => {
          if (v.type != 'button' && v.type != 'line') {
            newArr.push({
              label: v.label,
              porp: v.name,
              type: v.type,
            })
          }
        })
        return newArr
      },
      // 渲染字段
      fieldType(num) {
        let arr = []
        switch (num) {
          case 1:
            arr = this.pageSetting.dialog.form.field
            break
          case 2:
            arr = this.pageSetting.dialog.form.fieldMapping
            break
          case 3:
            arr = this.pageSetting.dialog.form.fieldMapping3
            break
          case 4:
            arr = this.pageSetting.dialog.form.fieldMapping4
            break
        }
        return arr
      },
      // $sub返回
      eventInit() {
        for (let item in this.tables) {
          let index = Number(item.replace(/[^0-9]/gi, ''))
          // 分页之后返回的数据
          this.$sub(`AppApiPage_Table_on_${item}`, (page_arr) => {
            this.getTable(item).tablePage['#LIMIT#'] = page_arr[0].limit
            this.getTable(item).pageSize = page_arr[0].pageSize
            this.getTable(item).tablePage['#PAGE_SIZE#'] = page_arr[0].pageSize
            if (index == 1) {
              this.onSubmit(this.serData, this.getTable(item).tablePage, index)
            } else if (index == 2 || index == 3 || index == 4) {
              this.onSubmit(this.getTable(item).dbPost, this.getTable(item).tablePage, index)
            }
          })
          // 表格单选之后返回的数据--渲染修改的表格
          this.$sub(`AppApiPage_Table_editBtn_${item}`, (data_arr) => {
            this.DialogNum = index
            let arr = this.fieldType(index)
            this.dialogType = 'modify'
            arr.forEach((v) => {
              if (!v.hidden) {
                if (v.type == 'select') {
                  if (this.defaultDrop[v.name]) {
                    v.options = this.defaultDrop[v.name].data
                  }
                }
              }
            })

            this.fieldType(index).forEach((v) => {
              if (!v.hidden || v.isAppCheck) {
                if (v.type == 'input' || v.type == 'textarea' || v.type == 'textarea_in_out') {
                  this.formData[v.name] = data_arr[0][v.name] == undefined ? '' : data_arr[0][v.name]
                } else if (v.type == 'select') {
                  if (
                    // 存在，的情况
                    v.name == 'FILE_TYPE' &&
                    data_arr[0]['FILE_TYPE'] != ''
                  ) {
                    data_arr[0][v.name].indexOf(',') != -1
                      ? (this.formData[v.name] = data_arr[0][v.name].split(','))
                      : (this.formData[v.name] = [data_arr[0][v.name]])
                  } else {
                    this.formData[v.name] = data_arr[0][v.name]
                  }
                }
              }
              if (data_arr[0].DAO_SP_PARAMS) {
                this.formData.DAO_SP_PARAMS = data_arr[0].DAO_SP_PARAMS
              }
            })
            console.log(this.formData)
            this.dialogVisible = !this.dialogVisible
          })
          this.$sub(`AppApiPage_Table_delBtn_${item}`, (data_arr) => {
            this.$confirm(translateTitle('Dams.ApplicationInterface.确定删除该应用接口信息'), translateTitle('Dams.ApplicationInterface.提示'), {
              confirmButtonText: translateTitle('Dams.ApplicationInterface.确定'),
              cancelButtonText: translateTitle('Dams.ApplicationInterface.取消'),
              type: 'warning',
            })
              .then(async () => {
                this.deleteNum = index
                this.delectName = data_arr[0].API_NAME
                this.delData = data_arr[0]
                this.confirmDelet()
              })
              .catch((e) => {
                console.log(e)
              })
          })
          this.$sub(`AppApiPage_Table_RefreshBtn_${item}`, (data_arr) => {
            this.isRefresh = true
            this.Refresh(data_arr[0])
          })
          // 复选框
          this.$sub(`AppApiPage_Table_checkbox_${item}`, (data_arr) => {
            console.log('复选框', data_arr[0])
            this.DialogNum = index
            if (index == 1) {
              this.checkboxData = data_arr[0]
            } else {
              this['checkboxData' + index] = data_arr[0]
            }
          })
          this.unsubs.push(`AppApiPage_Table_checkbox_${item}`)
          this.unsubs.push(`AppApiPage_Table_on_${item}`)
          this.unsubs.push(`AppApiPage_Table_editBtn_${item}`)
          this.unsubs.push(`AppApiPage_Table_delBtn_${item}`)
          this.unsubs.push(`AppApiPage_Table_RefreshBtn_${item}`)
        }
        // 双击t1表格
        this.$sub('AppApiPage_Table_clickOne_t1', (page_arr) => {
          console.log(page_arr)
          if (this.isRefresh) return
          let arr = [2, 3, 4]
          for (let item of arr) {
            this.getTable(`t1`).dbClick = page_arr[0]
            this.getTable(`t1`).dbPost = {
              API_NAME: page_arr[0].API_NAME,
              SUB_SYSTEM: page_arr[0].SUB_SYSTEM,
            }
            this.getTable(`t${item}`).dbPost = {
              API_NAME: page_arr[0].API_NAME,
              SUB_SYSTEM: page_arr[0].SUB_SYSTEM,
            }
            this.onSubmit(this.getTable(`t1`).dbPost, this.getTable(`t${item}`).tablePage, item)
            this.tabName = 'second'
            // 所属子系统给第三步
            this.threeObj['SUB_SYSTEM'] = page_arr[0]['SUB_SYSTEM']
            this.threeObj['API_NAME'] = page_arr[0]['API_NAME']
          }
        })
        this.unsubs.push('AppApiPage_Table_clickOne_t1')
        // 双击第二步表格
        this.$sub('AppApiPage_Table_clickOne_t2', (page_arr) => {
          console.log('page_arr[0]', page_arr[0])
          this.tabName = 'thrid'
          // 追加原报文ID给第三步
          this.threeObj['MSG_DATA_ID'] = page_arr[0]['MSG_DATA_ID']
          this.threeObj.isclick2 = true
        })
        this.unsubs.push('AppApiPage_Table_clickOne_t2')
        // 全选
        this.$sub('AppApiPage_Table_checkboxAll_t1', (data_arr) => {
          console.log('全选sub', data_arr[0])
          this.checkboxData = data_arr[0]
        })
        this.unsubs.push('AppApiPage_Table_checkboxAll_t1')
        //t1搜索提交后返回数据
        this.$sub('AppApiPage_forms_on_search', (data_arr) => {
          this.serData = data_arr[0]
          this.onSubmit(
            this.serData,
            {
              '#LIMIT#': 1,
              '#PAGE_SIZE#': 50,
            },
            1
          )
          this.tabName = 'first'
          this.threeObj = {
            isclick2: false,
          }
          this.tables.t1.tablePage['#LIMIT#'] = 1
          this.tables.t2.tableList = []
          this.tables.t3.tableList = []
          this.tables.t4.tableList = []
        })
        this.unsubs.push('AppApiPage_forms_on_search')

        // 模态框里面的确定按钮
        this.$sub('AppApiPage_forms_on_dialog', (data_arr) => {
          console.log(data_arr, this.dialogType, this.addPostUrl)
          if (data_arr[0] == '提交') {
            if (this.isSql() && !this.testSql) {
              this.$message({
                message: translateTitle('Dams.ApplicationInterface.请先进行sql验证'),
                type: 'warning',
              })
              return
            }
            // 确定按钮
            if (this.dialogType == 'add') {
              this.dialogFuc(this.addPostUrl)
            } else if (this.dialogType == 'modify') {
              this.dialogFuc(this.modifyPostUrl)
            }
          } else if (data_arr[0] == '校验SQL') {
            if (this.isSql()) {
              this.dialogFuc('dams.sql.field.map.sql.test')
              return
            } else {
              console.log('不需要你去校验')
            }
          }
        })
        this.unsubs.push('AppApiPage_forms_on_dialog')
        this.$sub('AppApiPage_Table_otherBtn_portForbidden', (data) => {
          this.disableApi(data[0])
        })
      },
      // 模态框里面确认之后接口请求函数
      dialogFuc(method) {
        if (this.formData.FILE_TYPE) {
          this.formData.FILE_TYPE = this.formData.FILE_TYPE.toString()
        }
        let p = cloneDeep(this.formData)
        console.log(p)
        if (p.DAO_SP_PARAMS_IN != undefined && p.DAO_SP_PARAMS_OUT != undefined) {
          if (p.DAO_SP_PARAMS_IN[p.DAO_SP_PARAMS_IN.length - 1] == ';') {
            p.DAO_SP_PARAMS = p.DAO_SP_PARAMS_IN + p.DAO_SP_PARAMS_OUT
          } else {
            p.DAO_SP_PARAMS = p.DAO_SP_PARAMS_IN + ';' + p.DAO_SP_PARAMS_OUT
          }
        }
        let pageSetDialog = this.pageSetting.dialog.form
        let arr = pageSetDialog.field.concat(pageSetDialog.fieldMapping, pageSetDialog.fieldMapping3, pageSetDialog.fieldMapping4)
        let keys = arr.filter((el) => el.type == 'input')
        let url = `${this.configSetting.domain}${this.configSetting.baseUrl}`
        for (const key in p) {
          const element = p[key]
          if (element && keys.find((el) => el.name == key)) {
            p[key] = trim(element)
          }
        }
        console.log(p)
        getList(url, {
          method: method,
          data: JSON.stringify(p),
        })
          .then((res) => {
            if (res.code == '00000') {
              this.$message({
                message: res.msg,
                type: 'success',
              })

              let postInfo = {}

              switch (this.DialogNum) {
                case 1:
                  postInfo = this.serData
                  break
                default:
                  postInfo = {
                    API_NAME: this.tables[`t1`].dbClick.API_NAME,
                    SUB_SYSTEM: this.tables[`t1`].dbClick.SUB_SYSTEM,
                  }
                  break
              }

              if (method == 'dams.sql.field.map.sql.test') {
                this.testSql = true
              } else {
                this.formData = {}
                this.dialogVisible = false
                this.testSql = false

                this.onSubmit(postInfo, this.getTable(this.DialogNum).tablePage, this.DialogNum)
              }
            } else {
              this.testSql = false
              this.$message({
                message: translateTitle('Dams.ApplicationInterface.校验失败'),
                type: 'error',
              })
            }
          })
          .catch((e) => {
            if (e.code == 'S9999') {
              this.testSql = false
              // console.log('this.testSql', this.testSql)
            }
          })
      },
      // 是否需要校验SQL
      isSql() {
        let fieldArr = this.fieldType(this.DialogNum)
        var someSql = fieldArr.some(function (item) {
          return item.label == 'SQL配置'
        })
        if (!someSql) {
          return false
        }
        let arr = []
        arr = fieldArr.filter((obj) => {
          return obj.isSqlTest
        })

        var someSqlTrue = arr.some((item) => {
          return !!this.formData[item.name] != false
        })
        return someSql && someSqlTrue
      },
      // 表格一接口函数
      onSubmit(data, tablePage, num) {
        let postUrl = ''
        if (num == 1) {
          this.postData = {
            ...data,
            ...tablePage,
          }
          postUrl = this.pageSetting.search.form.method
        } else if (num == 2) {
          this.postData = {
            ...data,
            ...tablePage,
          }
          postUrl = 'dams.sql.field.map.query'
        } else if (num == 3) {
          this.postData = {
            ...data,
            ...tablePage,
          }
          postUrl = 'dams.sql.add.map.query'
        } else if (num == 4) {
          this.postData = {
            ...data,
            ...tablePage,
          }
          postUrl = 'dams.field.map.query'
        }
        this.tableLoading = true
        let url = `${this.configSetting.domain}${this.configSetting.baseUrl}`
        this[`loading${num}`] = true
        getList(url, {
          method: postUrl,
          data: JSON.stringify(this.postData),
        }).then((res) => {
          if (res.code == '00000') {
            this[`loading${num}`] = false
            let dataName = ''
            switch (num) {
              case 1:
                dataName = 'dams.handle.flow.table.query'
                break
              case 2:
                dataName = 'dams.sql.field.map.query'
                break
              case 3:
                dataName = 'dams.sql.add.map.query'
                break
              case 4:
                dataName = 'dams.field.map.query'
                break
            }
            this.getTable(num).tableList = res.data[dataName].data
            this.getTable(num).count = res.data[dataName].count
          } else {
            this.$message({
              message: res.msg,
              type: 'warning',
            })
          }
          this.tableLoading = false
        })
      },
      // 添加下拉选//等待处理
      addSelect() {
        this.postData = {
          ...this.tables.t1.tablePage,
        }
        let url = `${this.configSetting.domain}${this.configSetting.baseUrl}`
        getList(url, {
          method: 'dams.handle.flow.query.options',
          data: JSON.stringify(this.postData),
        }).then((res) => {
          if (res.code == '00000') {
            this.defaultDrop = res.data
          } else {
            this.$message({
              message: res.msg,
              type: 'warning',
            })
          }
        })
      },
      showDialog(type, num) {
        // console.log('type, num', type, num)
        this.DialogNum = num
        this.dialogType = type
        let arr = this.fieldType(num)
        if (type == 'add') {
          arr.forEach((v) => {
            if (!v.hidden || v.isAppCheck) {
              // 下拉选
              if (v.type == 'select') {
                if (this.defaultDrop[v.name]) {
                  v.options = this.defaultDrop[v.name].data
                  let active = this.defaultDrop[v.name].data.find((it) => {
                    return it.ACTIVE == 'Y'
                  })
                  if (v.name == 'SUB_SYSTEM' && num != 1) {
                    this.formData[v.name] = this.getTable(num - 1).dbClick[v.name]
                  } else if (v.name == 'API_MSG_DOBIZLOGIC') {
                    this.formData[v.name] = ''
                  } else {
                    if (active) {
                      this.formData[v.name] = active.CODE
                    } else {
                      this.formData[v.name] = ''
                    }
                  }
                } else {
                  this.formData[v.name] = v.value || ''
                }

                if (v.isFixed) {
                  if (v.name == 'FILE_SERVER_TYPE' || v.name == 'FILE_SAVE_PATH_TYPE' || v.name == 'DAO_INSERT_SQL_RULE') {
                    this.formData[v.name] = ''
                  } else {
                    this.formData[v.name] = v.options[0].CODE
                  }

                  return
                }
              }
              // input和textarea
              else if (v.type == 'input' || v.type == 'textarea' || v.type == 'textarea_in_out') {
                // 第二三四步渲染模态框
                if (v.name == 'API_NAME' && num != 1) {
                  this.formData[v.name] = this.getTable(num - 1).dbClick[v.name]
                } else if (!!v.value != false) {
                  // 有默认值渲染
                  this.formData[v.name] = v.value
                } else {
                  // 没有默认值渲染空
                  this.formData[v.name] = ''
                }
              }
              //特殊操作哈哈哈哈 提取后的报文数据ID==接口名称
              if (v.name == 'MSG_DATA_ID') {
                this.formData[v.name] = this.formData['API_NAME']
              } else if (v.name == 'DB_ID') {
                //SQL校验数据源ID==所属子系统
                this.formData[v.name] = this.formData['SUB_SYSTEM']
              }
              // 第三拿第一第二给的数据
              if (num == 3 || num == 4) {
                this.formData['SUB_SYSTEM'] = this.threeObj['SUB_SYSTEM']
                // 第三部拿第一第二给的数据
                if (this.threeObj.isclick2) {
                  this.formData['MSG_DATA_ID'] = this.threeObj['MSG_DATA_ID']
                }
              }
              if (num != 1) {
                this.formData['API_NAME'] = this.threeObj['API_NAME']
                this.formData['SUB_SYSTEM'] = this.threeObj['SUB_SYSTEM']
              }
            }
          })
          this.dialogVisible = true
        }
      },
      // 确认删除啊
      confirmDelet() {
        let postUrl = ''
        let url = `${this.configSetting.domain}${this.configSetting.baseUrl}`
        switch (this.deleteNum) {
          case 1:
            postUrl = 'dams.handle.flow.del'
            break
          case 2:
            postUrl = 'dams.sql.field.map.del'
            break
          case 3:
            postUrl = 'dams.sql.add.map.del'
            break
          case 4:
            postUrl = 'dams.field.map.del'
            break
        }

        getList(url, {
          method: postUrl,
          data: JSON.stringify({
            ID: this.delData.ID,
            API_NAME: this.delData.API_NAME,
            SUB_SYSTEM: this.delData.SUB_SYSTEM,
          }),
        }).then((res) => {
          if (res.code == '00000') {
            this.$message({
              message: res.msg,
              type: 'success',
            })
            let postInfo = {}
            switch (this.deleteNum) {
              case 1:
                postInfo = this.serData
                break
              default:
                postInfo = {
                  API_NAME: this.tables[`t1`].dbClick.API_NAME,
                  SUB_SYSTEM: this.tables[`t1`].dbClick.SUB_SYSTEM,
                }
                break
            }
            this.$message({
              type: 'success',
              message: translateTitle('Dams.ApplicationInterface.删除成功'),
            })
            this.onSubmit(postInfo, this.getTable(this.deleteNum).tablePage, this.deleteNum)
          } else {
            this.$message({
              message: res.msg,
              type: 'warning',
            })
          }
        })
      },
      // 刷新token
      Refresh(data) {
        let url = `${this.configSetting.domain}${this.configSetting.baseUrl}`
        getList(url, {
          method: 'dams.handle.flow.refresh.cache',
          data: JSON.stringify({
            API_NAME: data.API_NAME,
            SUB_SYSTEM: data.SUB_SYSTEM,
          }),
        }).then((res) => {
          if (res.code == '00000') {
            this.$message({
              message: res.msg,
              type: 'success',
            })
            this.isRefresh = false
            this.onSubmit(
              this.serData,
              {
                '#LIMIT#': 1,
                '#PAGE_SIZE#': 50,
              },
              1
            )
          } else {
            this.$message({
              message: res.msg,
              type: 'warning',
            })
          }
        })
      },
    },
  }
</script>
<style lang="scss">
  .w-full {
    .el-tabs__header {
      margin: 0px !important;
    }
  }
</style>
<style lang="scss" scoped>
  .item_line {
    width: calc(92% + 30px) !important;
    border-bottom: 1px dashed #ccc;
    margin: 10px 0px !important;
    .line {
      width: 100% !important;
      height: 30px;
      background: rgb(221, 220, 220) !important;
      font-size: 20px !important;
      padding: 0px 20px;
    }
  }
  .item_textarea {
    width: calc(92% + 30px) !important;
  }
  .w-full {
    .el-tabs__header {
      margin: 0px !important;
    }
    .el-row {
      margin-bottom: 20px;
      &:last-child {
        margin-bottom: 0;
      }
    }
    .el-col {
      border-radius: 4px;
    }
    .bg-purple-dark {
      background: #99a9bf;
    }
    .bg-purple {
      background: #f8f8f8;
      padding: 2px 2px;
    }
    .bg-purple-light {
      background: #e5e9f2;
    }
    .grid-content {
      display: flex;
      justify-content: flex-start;
      border-radius: 4px;
      padding: 10px 0;
    }
    .vui-upload {
      > div {
        display: flex;
        justify-content: flex-start;
      }
    }
    .row-bg {
      padding: 10px 0;
      background-color: #f9fafc;
    }
    .dialog-footer {
      text-align: center;
    }
    :deep() {
      .el-tabs__item {
        font-size: 12px;
        height: 24px;
        line-height: 24px;
      }
      .style_dialog {
        .el-form--inline .el-form-item {
          width: 23%;
          display: inline-block;
          margin-bottom: 10px;
        }
        .box .el-form-item {
          flex-grow: 1; /* default 0 */
        }
        .el-form-item__label {
          display: block;
          text-align: left;
          line-height: 24px;
          font-size: 12px;
        }
        .el-form-item__content {
          width: 100%;
        }
        // .el-select {
        //   width: 100%;
        // }
        .item_button {
          display: block !important;
          width: 100% !important;
          text-align: center;
        }
      }
    }
    .line {
      width: 100% !important;
      height: 30px;
      background: rgb(221, 220, 220) !important;
      font-size: 20px !important;
      padding: 0px 20px;
    }
  }
</style>
